<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import axios from 'axios'

const router = useRouter()
const isCollapse = ref(false)
const activeMenu = ref('')
const menuData = ref([])
const userInfo = ref({
  name: '',
  role: { name: '' },
  department: { name: '' }
})

// 处理菜单点击
const handleMenuClick = (menu) => {
  if (menu.url) {
    router.push(menu.url)
  }
}

// 处理折叠菜单
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 将权限数据转换为菜单结构
const transformPermissionsToMenu = (permissions) => {
  // 找出所有父级菜单
  const parentMenus = permissions.filter(item => item.pid === null)
  
  // 为每个父菜单找到对应的子菜单
  const result = parentMenus.map(parent => {
    const children = permissions.filter(item => item.pid === parent.id)
    return {
      id: parent.id,
      title: parent.name,
      url: parent.url,
      icon: getIconByName(parent.name),
      children: children.map(child => ({
        id: child.id,
        title: child.name,
        url: child.url,
        icon: getIconByName(child.name)
      }))
    }
  })
  
  return result
}

// 根据菜单名称返回对应的图标
const getIconByName = (name) => {
  const iconMap = {
    '医生管理': 'UserFilled',
    '医生列表': 'List',
    '预约管理': 'Calendar',
    '患者管理': 'User',
    '药房管理': 'FirstAidKit',
    '默认': 'Menu'
  }
  
  return iconMap[name] || iconMap['默认']
}

const loading = ref(false)
const doctorList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加医生')
const formLoading = ref(false)
const departmentList = ref([])

// 表单数据
const form = ref({
  id: null,
  name: '',
  price: 30,
  department_id: '',
  title: '',
  tags: '',
  introduction: '',
  campus: '东院',
  avatar: null
})

// 表单规则
const rules = {
  name: [{ required: true, message: '请输入医生姓名', trigger: 'blur' }],
  department_id: [{ required: true, message: '请选择所属科室', trigger: 'change' }],
  title: [{ required: true, message: '请输入职称', trigger: 'blur' }]
}

// 获取医生列表数据
const fetchDoctors = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('http://127.0.0.1:8000/manage/doctors/', {
      params: {
        page: currentPage.value,
        page_size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    if (response.data.code === 200) {
      doctorList.value = response.data.data.results
      total.value = response.data.data.total
    } else {
      ElMessage.error(response.data.message || '获取医生列表失败')
    }
  } catch (error) {
    ElMessage.error('获取医生列表失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 获取科室列表
const fetchDepartments = async () => {
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get('http://127.0.0.1:8000/manage/departments/', {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    if (response.data.code === 200) {
      departmentList.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('获取科室列表失败：' + error.message)
  }
}

// 处理添加按钮点击
const handleAdd = () => {
  dialogTitle.value = '添加医生'
  form.value = {
    id: null,
    name: '',
    price: 30,
    department_id: '',
    title: '',
    tags: '',
    introduction: '',
    campus: '东院',
    avatar: null
  }
  dialogVisible.value = true
}

// 处理编辑按钮点击
const handleEdit = (row) => {
  dialogTitle.value = '编辑医生'
  form.value = {
    ...row,
    department_id: row.department_id
  }
  dialogVisible.value = true
}

// 处理删除按钮点击
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该医生吗？', '提示', {
      type: 'warning'
    })
    const token = localStorage.getItem('token')
    const response = await axios.delete(`http://127.0.0.1:8000/manage/doctors/${row.id}/`, {
      headers: {
        'Authorization': `Bearer ${token}`
      }
    })
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      fetchDoctors()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message)
    }
  }
}

// 处理表单提交
const handleSubmit = async () => {
  formLoading.value = true
  try {
    // 构建请求数据
    const requestData = {
      name: form.value.name,
      department_id: form.value.department_id,
      title: form.value.title,
      price: form.value.price,
      tags: form.value.tags || '',
      introduction: form.value.introduction || '',
      campus: form.value.campus || '东院',
      avatar: '/uploads/doctors/d8ba61281d3b7b3df4f93d8bd06d9f6.png'  // 使用固定的默认头像
    }

    const token = localStorage.getItem('token')
    const url = form.value.id
      ? `http://127.0.0.1:8000/manage/doctors/${form.value.id}/`
      : 'http://127.0.0.1:8000/manage/doctors/'
    
    const method = form.value.id ? 'put' : 'post'
    const response = await axios({
      method,
      url,
      data: requestData,
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
      }
    })

    if (response.data.code === 200) {
      ElMessage.success(form.value.id ? '修改成功' : '添加成功')
      dialogVisible.value = false
      fetchDoctors()
    } else {
      ElMessage.error(response.data.message || (form.value.id ? '修改失败' : '添加失败'))
    }
  } catch (error) {
    ElMessage.error((form.value.id ? '修改' : '添加') + '失败：' + error.message)
  } finally {
    formLoading.value = false
  }
}

// 处理头像上传
const handleAvatarChange = (file) => {
  form.value.avatar = file.raw
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchDoctors()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  fetchDoctors()
}

onMounted(() => {
  fetchDoctors()
  fetchDepartments()
  // 获取存储的权限数据
  const permissionsStr = localStorage.getItem('permissions')
  if (permissionsStr) {
    const permissions = JSON.parse(permissionsStr)
    menuData.value = transformPermissionsToMenu(permissions)
  }
  
  // 获取用户信息
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    userInfo.value = JSON.parse(userInfoStr)
  }
})
</script>

<template>
  <div class="layout-container">
    <!-- 侧边栏 -->
    <div class="sidebar" :class="{ 'is-collapsed': isCollapse }">
      <div class="logo-container">
        <img src="https://via.placeholder.com/40" alt="Logo" class="logo" />
        <span v-if="!isCollapse" class="logo-text">七星医疗系统</span>
      </div>
      
      <el-scrollbar>
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          :collapse="isCollapse"
          background-color="#001529"
          text-color="#fff"
          active-text-color="#1890ff"
          unique-opened
          router
        >
          <template v-for="menu in menuData" :key="menu.id">
            <!-- 有子菜单的情况 -->
            <el-sub-menu v-if="menu.children && menu.children.length > 0" :index="menu.url || menu.id.toString()">
              <template #title>
                <el-icon>
                  <component :is="menu.icon"></component>
                </el-icon>
                <span>{{ menu.title }}</span>
              </template>
              
              <el-menu-item 
                v-for="subMenu in menu.children" 
                :key="subMenu.id" 
                :index="subMenu.url"
                @click="handleMenuClick(subMenu)"
              >
                <el-icon>
                  <component :is="subMenu.icon"></component>
                </el-icon>
                <span>{{ subMenu.title }}</span>
              </el-menu-item>
            </el-sub-menu>
            
            <!-- 无子菜单的情况 -->
            <el-menu-item 
              v-else 
              :index="menu.url"
              @click="handleMenuClick(menu)"
            >
              <el-icon>
                <component :is="menu.icon"></component>
              </el-icon>
              <span>{{ menu.title }}</span>
            </el-menu-item>
          </template>
        </el-menu>
      </el-scrollbar>
    </div>

    <!-- 主内容区 -->
    <div class="main-container">
      <!-- 顶部导航栏 -->
      <div class="header">
        <div class="header-left">
          <el-icon class="collapse-btn" @click="toggleCollapse">
            <Fold v-if="!isCollapse" />
            <Expand v-else />
          </el-icon>
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/about' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>医生列表</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div class="header-right">
          <el-dropdown trigger="click">
            <div class="user-info">
              <el-avatar size="small" src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" />
              <span class="username">{{ userInfo.name }}</span>
              <el-icon><CaretBottom /></el-icon>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item>
                  <span>{{ userInfo.role?.name || '未知角色' }}</span>
                </el-dropdown-item>
                <el-dropdown-item>
                  <span>{{ userInfo.department?.name || '未知部门' }}</span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </div>

      <!-- 医生列表内容区 -->
      <div class="content">
        <div class="doctor-list">
          <div class="page-header">
            <h2>医生列表</h2>
            <el-button type="primary" @click="handleAdd">
              <el-icon><Plus /></el-icon>添加医生
            </el-button>
          </div>

          <el-card class="table-card">
            <el-table
              v-loading="loading"
              :data="doctorList"
              border
              style="width: 100%"
            >
              <el-table-column prop="id" label="ID" width="80" />
              <el-table-column prop="name" label="姓名" width="120" />
              <el-table-column prop="title" label="职称" width="120" />
              <el-table-column prop="department_name" label="科室" width="120" />
              <el-table-column prop="campus" label="医院" width="200" />
              <el-table-column prop="price" label="挂号费" width="100">
                <template #default="{ row }">
                  ¥{{ row.price }}
                </template>
              </el-table-column>
              <el-table-column prop="tags" label="专长" width="150">
                <template #default="{ row }">
                  <el-tag v-if="row.tags" size="small">{{ row.tags }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="200" fixed="right">
                <template #default="{ row }">
                  <el-button-group>
                    <el-button type="primary" size="small" @click="handleEdit(row)">
                      编辑
                    </el-button>
                    <el-button type="danger" size="small" @click="handleDelete(row)">
                      删除
                    </el-button>
                  </el-button-group>
                </template>
              </el-table-column>
            </el-table>

            <div class="pagination-container">
              <el-pagination
                v-model:current-page="currentPage"
                v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </el-card>
        </div>

        <!-- 添加/编辑对话框 -->
        <el-dialog
          v-model="dialogVisible"
          :title="dialogTitle"
          width="500px"
          @close="dialogVisible = false"
        >
          <el-form
            ref="formRef"
            :model="form"
            :rules="rules"
            label-width="100px"
            :disabled="formLoading"
          >
            <el-form-item label="医生姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入医生姓名" />
            </el-form-item>

            <el-form-item label="所属科室" prop="department_id">
              <el-select v-model="form.department_id" placeholder="请选择科室">
                <el-option
                  v-for="dept in departmentList"
                  :key="dept.id"
                  :label="dept.parent_name ? `${dept.parent_name}-${dept.name}` : dept.name"
                  :value="dept.id"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="职称" prop="title">
              <el-input v-model="form.title" placeholder="请输入职称" />
            </el-form-item>

            <el-form-item label="挂号费" prop="price">
              <el-input-number v-model="form.price" :min="0" :precision="2" :step="10" />
            </el-form-item>

            <el-form-item label="医疗标签" prop="tags">
              <el-input v-model="form.tags" placeholder="请输入医疗标签，用逗号分隔" />
            </el-form-item>

            <el-form-item label="执业院区" prop="campus">
              <el-input v-model="form.campus" placeholder="请输入执业院区" />
            </el-form-item>

            <el-form-item label="医生简介" prop="introduction">
              <el-input
                v-model="form.introduction"
                type="textarea"
                :rows="3"
                placeholder="请输入医生简介"
              />
            </el-form-item>
          </el-form>

          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialogVisible = false">取消</el-button>
              <el-button type="primary" :loading="formLoading" @click="handleSubmit">
                确定
              </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<style scoped>
.layout-container {
  display: flex;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.sidebar {
  width: 220px;
  height: 100%;
  background-color: #001529;
  transition: width 0.3s;
  overflow: hidden;
  box-shadow: 2px 0 6px rgba(0, 21, 41, 0.35);
  z-index: 10;
}

.sidebar.is-collapsed {
  width: 64px;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 16px;
  overflow: hidden;
  background-color: #002140;
}

.logo {
  width: 32px;
  height: 32px;
  border-radius: 50%;
}

.logo-text {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  margin-left: 12px;
  white-space: nowrap;
}

.sidebar-menu {
  border-right: none;
}

.main-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.header {
  height: 60px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 21, 41, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 16px;
}

.header-left {
  display: flex;
  align-items: center;
}

.collapse-btn {
  font-size: 20px;
  cursor: pointer;
  margin-right: 16px;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin: 0 8px;
  color: #333;
}

.content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f0f2f5;
}

.doctor-list {
  height: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-weight: 500;
}

.table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 